package com.example.library.picture;

import android.annotation.SuppressLint;
import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.RecyclerView;

import com.example.library.R;
import com.squareup.picasso.Picasso;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @author: xtxiaolu
 * @date: 2023/8/31
 * 图片浏览简单控件
 */
public class PictureRecyclerView extends RecyclerView {
    private Context mContext;
    private List<String> photosList = new ArrayList<>();
    private PhotoAdapter adapter;
    private ItemTouchHelper touchHelper;

    private boolean editable = true;

    // 接口定义
    public interface OnItemClickListener {
        void onItemClick(View view, int position);
    }

    public interface OnDeleteClickListener {
        void onDeleteClick(View view, int position);
    }

    private OnItemClickListener onItemClickListener;
    private OnDeleteClickListener onDeleteClickListener;

    public PictureRecyclerView(Context context) {
        super(context);
        this.mContext = context;
        init();
    }

    public PictureRecyclerView(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.mContext = context;
        init();
    }

    public PictureRecyclerView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        this.mContext = context;
        init();
    }

    private void init() {
        setLayoutManager(new GridLayoutManager(getContext(), 3));
        adapter = new PhotoAdapter();
        setAdapter(adapter);
        touchHelper = new ItemTouchHelper(new ItemTouchHelperCallback());
        touchHelper.attachToRecyclerView(this);
    }

    public void setEditable(boolean editable) {
        this.editable = editable;
        adapter.notifyDataSetChanged();
    }

    public void addPhoto(String photoUrl) {
        if (photosList.size() < 9) {
            photosList.add(photoUrl);
            adapter.notifyDataSetChanged();
        }
    }

    /**
     * 设置图片路径数据集合
     *
     * @param listUri
     */
    public void setData(List<String> listUri) {
        photosList.clear();
        photosList.addAll(listUri);
        adapter.notifyDataSetChanged();
    }

    public void refreshAdapter(){
        adapter.notifyDataSetChanged();
    }

    public void removePhoto(int position) {
        if (position >= 0 && position < photosList.size()) {
            photosList.remove(position);
            adapter.notifyItemRemoved(position);
        }
    }

    public List<String> getPhotos() {
        return photosList;
    }

    // 设置点击事件监听器
    public void setOnItemClickListener(OnItemClickListener listener) {
        this.onItemClickListener = listener;
    }

    // 设置删除按钮点击事件监听器
    public void setOnDeleteClickListener(OnDeleteClickListener listener) {
        this.onDeleteClickListener = listener;
    }

    private class PhotoAdapter extends RecyclerView.Adapter<PhotoAdapter.PhotoViewHolder> implements ItemTouchHelperAdapter {

        @Override
        public PhotoViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = View.inflate(getContext(), R.layout.item_photo, null);
            return new PhotoViewHolder(view);
        }

        @Override
        public void onBindViewHolder(PhotoViewHolder holder, @SuppressLint("RecyclerView") int position) {
            if (position < photosList.size()) {
                String photoUrl = photosList.get(position);
                Picasso.with(mContext).load(photoUrl).into(holder.imageView);
                holder.deleteView.setVisibility(editable ? View.VISIBLE : View.GONE);

                // 设置照片点击事件
                holder.imageView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (onItemClickListener != null) {
                            onItemClickListener.onItemClick(v, position);
                        }
                    }
                });

                // 设置删除按钮点击事件
                holder.deleteView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (onDeleteClickListener != null) {
                            // 获取当前项的位置 不能直接删除 position 因为如果删除到最后一条的角标为0
                            int itemPosition = holder.getAbsoluteAdapterPosition();
                            if (itemPosition != RecyclerView.NO_POSITION) {
                                photosList.remove(itemPosition);
                                notifyItemRemoved(itemPosition);
                                onDeleteClickListener.onDeleteClick(v, itemPosition);
                            }
//                            onDeleteClickListener.onDeleteClick(v, position);
                        }
                    }
                });
            } else {
                holder.imageView.setImageResource(R.drawable.ic_add_photo);
                holder.deleteView.setVisibility(View.GONE);
            }
        }

        @Override
        public int getItemCount() {
            return Math.min(photosList.size() + 1, 9);
        }

        @Override
        public void onItemMove(int fromPosition, int toPosition) {
            if (fromPosition < photosList.size() && toPosition < photosList.size()) {
                Collections.swap(photosList, fromPosition, toPosition);
                notifyItemMoved(fromPosition, toPosition);
            }
        }

        @Override
        public void onItemDismiss(int position) {
            if (position < photosList.size()) {
                photosList.remove(position);
                notifyItemRemoved(position);
            }
        }

        class PhotoViewHolder extends RecyclerView.ViewHolder {
            ImageView imageView;
            ImageView deleteView;

            PhotoViewHolder(View itemView) {
                super(itemView);
                imageView = itemView.findViewById(R.id.imageView);
                deleteView = itemView.findViewById(R.id.deleteView);
            }
        }
    }

    private class ItemTouchHelperCallback extends ItemTouchHelper.Callback {

        @Override
        public int getMovementFlags(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
            int dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN | ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT;
            int swipeFlags = 0;
            return makeMovementFlags(dragFlags, swipeFlags);
        }

        @Override
        public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder source, RecyclerView.ViewHolder target) {
            adapter.onItemMove(source.getAdapterPosition(), target.getAdapterPosition());
            return true;
        }

        @Override
        public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
            adapter.onItemDismiss(viewHolder.getAdapterPosition());
        }
    }

    private interface ItemTouchHelperAdapter {
        void onItemMove(int fromPosition, int toPosition);
        void onItemDismiss(int position);
    }
}